package cn.yj.alipay.service.handler;

import cn.yj.common.emums.PayFrom;
import cn.yj.common.entity.AliPayResult;
import cn.yj.common.exception.PayException;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayRequest;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 永健
 * @since 2022-02-17 20:53
 */
public class PcAlipay extends AbstractAliPay<AlipayRequest, AliPayResult> {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean support(PayFrom payFrom) {
        return PayFrom.PC == payFrom;
    }

    @Override
    public AliPayResult underOrder(AlipayRequest payRequest) throws PayException {
        AlipayTradePagePayRequest request = (AlipayTradePagePayRequest) payRequest;
        request.setNotifyUrl(config().getNotifyUrl());
        request.setReturnUrl(config().getReturnUrl());
        AlipayTradePagePayResponse response;
        AlipayTradePagePayModel bizModel = (AlipayTradePagePayModel) request.getBizModel();
        bizModel.setProductCode("FAST_INSTANT_TRADE_PAY");
        String errorMsg = "下单失败";
        AliPayResult aliPayResult = new AliPayResult();
        try {
            response = doPay().pageExecute(request);
            logger().info(response.toString());
            if (response.isSuccess()) {
                String bodyStr = response.getBody();
                String replace = bodyStr.replace("name=\"punchout_form\"", "name=\"punchout_form\" target=\"_blank\"");
                aliPayResult.setCode(response.getCode());
                aliPayResult.setSubCode(response.getSubCode());
                aliPayResult.setMsg(response.getMsg());
                aliPayResult.setSubMsg(response.getSubMsg());
                Map<String, Object> body = new HashMap<>();
                body.put("body", replace);
                aliPayResult.setBody(body);
                aliPayResult.setTotalAmount(response.getTotalAmount());
                aliPayResult.setOutTradeNo(response.getOutTradeNo());
                aliPayResult.setTradeNo(response.getTradeNo());
                aliPayResult.setSuccess(response.isSuccess());
                super.addPayOrderMonitor(getExpireTime(bizModel.getTimeExpire(),bizModel.getTimeoutExpress()),bizModel.getOutTradeNo(),this);
                return aliPayResult;
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            errorMsg = e.getMessage();
        }
        throw new PayException(errorMsg);
    }
}
